<template>
	<view class="page">
		<view class="m-b-sm">
			<up-swiper :list="swiperData"></up-swiper>
		</view>
		<!-- 使用模式 -->
		<view v-if="deviceCode && deviceBtId" class="layout g-card">
			<text class="module-title">充电时长</text>
			<div class="cell-list">
				<div class="cell-item" v-for="(item, index) in goodsList" :key="index"
					:class="{ 'is-active': currentId === item.id }" @click="itemChange(item.id)">
					<div class="content">
						<text class="duration">{{ item.duration }}分钟</text>
						<text class="des">{{ item.description }}</text>
					</div>
					<text class="price">¥{{ item.price }}</text>
				</div>
			</div>
			<view class="footer">
				<up-button v-if="!bluetoothIsOpen" color="#64c6ae" size="large" @click="openBluetooth"
					text="开启蓝牙"></up-button>
				<BindMobile v-else-if="!hasMobile" text="登录并开始充电" @onbind="submitCharging"></BindMobile>
				<up-button v-else color="#64c6ae" size="large" :loading="submitLoading" @click="submitCharging"
					text="开始充电"></up-button>
				<up-safe-bottom></up-safe-bottom>
			</view>
		</view>
		<!-- 展示模式 -->
		<view v-else>
			<div class="m-b">
				<up-button v-if="!bluetoothIsOpen" color="#64c6ae" size="large" @click="openBluetooth"
					text="开启蓝牙"></up-button>
				<up-button v-else color="#64c6ae" size="large" text="扫一扫开始充电" @click="openScan"></up-button>
			</div>
		</view>

		<view v-if="isAgent" class="m-t-lg">
			<up-button text="我是商家" :plain="true" @click="routerToBusiness"></up-button>
		</view>

		<view class="tips">
			<text class="title">温馨提示</text>
			<text class="des">1.安卓手机如无法连接设备，请打开手机蓝牙。</text>
			<text class="des">2.苹果手机如无法连接上设备，请打开手机设置->隐私->微信-蓝牙。</text>
		</view>
		<view style="text-align: center;">
			<button open-type="contact" class="contact-btn">加盟我们</button>
		</view>
	</view>
</template>

<script setup>
	// https://blog.csdn.net/qq_41687299/article/details/138107251
	// 蓝牙名称：AKZSCB0426
	// 设备码：AK312261630
	// https://aoke.idnlkj.com/miniapp/m_charge?deviceCode=AK312261630&type=2
	import useBt from '@/common/hooks/bt.js'
	import usePay from '@/common/hooks/pay.js'
	import api from '@/api/app.js'
	import useAppStore from '@/store/app.js'
	import {
		getQueryString,
	} from '@/common/utils/index.js'
	import bannerSrc from '@/static/index-banner.png'

	const appStore = useAppStore()
	const hasMobile = computed(() => appStore.hasMobile)
	const isAgent = computed(() => appStore.isAgent)
	const {
		initBluetooth,
		closeBluetooth,
		startBluetoothDevicesDiscovery,
		onBluetoothDeviceFound,
		createBLEConnection,
		getBLEDeviceServices,
		getBLEDeviceCharacteristics,
		sendCargeCommand,
		readChargeStatus,
		checkAndReconnectDevice,
	} = useBt()

	const {
		createWxPreOrder,
		checkOrder,
	} = usePay()

	const submitLoading = ref(false)
	const bluetoothIsOpen = ref(false)
	const bluetoothFindText = ref(false)
	const bluetoothFinded = ref(false)
	const deviceKey = 'deviceCode'
	const deviceId = ref('') // 真实的设备id
	const deviceCode = ref('') // 设备名称
	const deviceBtId = ref('')
	const goodsList = ref([])
	const currentId = ref('')
	const orderNumber = ref('')
	const bannerImg = ref(bannerSrc)
	const swiperData = reactive([bannerImg.value])


	// 切换选项
	function itemChange(id) {
		currentId.value = id
		orderNumber.value = ''
	}

	async function submitCharging() {
		// const deviceIsConnect = await checkAndReconnectDevice(deviceId.value)
		// if (!deviceIsConnect) {
		// 	console.log('断开了！！？？？')
		// 	// uni.showToast({
		// 	// 	icon: 'none',
		// 	// 	title: '设备已断开，重新连接中..'
		// 	// })
		// 	await connectBt(deviceId.value)
		// }
		try {
			const {
				status,
				charging,
				hours,
				errMsg,
				minutes
			} = await readChargeStatus()
			console.log('chargeData errMsg', errMsg)
			if (!status) {
				wx.showModal({
					title: '蓝牙已断开，请刷新页面后重试',
					content: '请稍后再试',
					showCancel: false,
				})
				return;
			}
			if (charging) {
				wx.showModal({
					title: '当前设备正在使用中',
					content: '请稍后再试',
					showCancel: false,
				})
				console.log('device is charging')
				return
			}
		} catch (e) {
			//TODO handle the exception
		}


		if (submitLoading.value) {
			return
		}

		if (orderNumber.value) {
			goPay()
			return
		}
		submitLoading.value = true
		api.createOrder({
			device_id: deviceCode.value,
			goods_id: currentId.value,
		}).then((res) => {
			const orderNum = res.data.data.order_number
			orderNumber.value = orderNum
			if (orderNum) {
				goPay()
			}
		}).catch(() => {
			submitLoading.value = false
		})
	}

	function goPay() {
		createWxPreOrder(orderNumber.value).then(() => {
			checkOrder(orderNumber.value).then((order) => {
				goCharging(order)
				uni.showToast({
					title: '支付成功',
					icon: 'succes',
					duration: 2000
				})
			}).catch(() => {
				uni.showToast({
					title: '支付结果查询失败',
					icon: 'none',
					duration: 2000
				})
			}).finally(() => {
				orderNumber.value = ''
			})
		}).finally(() => {
			submitLoading.value = false
		})
	}

	function goCharging(order) {
		const goods = order.goods[0];
		console.log('charging goods', goods)
		if (!goods) return
		let [hours, minutes] = convertMinutes(goods.duration)
		console.log('hours', hours)
		console.log('minutes', minutes)
		try {
			sendCargeCommand(hours, minutes).then(() => {
				console.log('开始充电')
				uni.redirectTo({
					url: '/pages/result/result?type=success&msg=支付成功&back=0'
				})
				closeBluetooth()
			})
		} catch (error) {}
	}

	function convertMinutes(duration) {
		const minutes = parseInt(duration)
		const hours = Math.floor(minutes / 60);
		const remainingMinutes = minutes % 60;
		return [hours, remainingMinutes];
	}


	// 获取蓝牙名称
	function getBtId() {
		return new Promise((resolve, reject) => {
			api.getBtId({
				device_id: deviceCode.value
			}).then(res => {
				const btId = res.data.data.bt_id || ''
				resolve(btId)
			}).catch(() => {
				reject()
			})
		})
	}

	// 初始化
	async function init() {
		if (!deviceCode.value) {
			return;
		}
		if (!appStore.isLogin) {
			await appStore.login()
		}
		let systemInfo = uni.getSystemInfoSync()
		const osName = systemInfo.osName;
		if (osName === 'ios') {
			openBt()
			getGoodsList()
		} else {
			openFuzzyLocationAndInit()
		}
		// const btId = await getBtId()
		// deviceBtId.value = btId
	}

	function openFuzzyLocationAndInit() {
		wx.getFuzzyLocation({
			type: 'gcj02',
			success(res) {
				console.log('获取模糊位置信息成功:', res);
				openBt()
				getGoodsList()
			},
			fail(err) {
				if (err.errno === 103) {
					// 用户拒绝授权获取模糊位置
					wx.showModal({
						title: '授权提示',
						content: '需要使用模糊位置信息，请前往设置开启位置信息权限',
						success(res) {
							if (res.confirm) {
								// 用户点击确认，打开设置页面
								wx.openSetting({
									success(settingRes) {
										if (settingRes.authSetting['scope.userFuzzyLocation']) {
											// 用户重新开启了模糊位置权限
											wx.getFuzzyLocation({
												type: 'gcj02',
												success(res) {
													console.log('重新获取模糊位置信息成功:', res);
													openBt()
													getGoodsList()
												},
												fail(err) {
													console.error('重新获取模糊位置信息失败:', err);
												}
											});
										} else {
											console.log('用户未开启模糊位置信息权限');
										}
									},
									fail(settingErr) {
										console.error('打开设置页面失败:', settingErr);
									}
								});
							} else {
								console.log('用户取消了授权提示');
							}
						}
					});
				} else {
					console.error('获取模糊位置信息失败:', err);
				}
			}
		});
	}

	// 打开系统设置，引到用户打开蓝牙
	function openBluetooth() {
		wx.openSetting({ // 打开小程序设置界面
			success: (res) => {
				if (res.authSetting['scope.bluetooth']) {
					// 用户打开了蓝牙权限，重新初始化蓝牙
					openBt();
				} else {
					wx.showToast({
						title: '请授权使用蓝牙',
						icon: 'error'
					});
				}
			}
		});
	}

	// 初始化蓝牙
	function openBt() {
		// 初始化蓝牙模块
		initBluetooth().then(() => {
			bluetoothIsOpen.value = true
			findDevice()
		}).catch(() => {
			wx.showModal({
				title: '蓝牙未开启',
				content: '请先开启蓝牙功能，然后重试。',
				confirmText: '去设置',
				success: (res) => {
					if (res.confirm) {
						openBluetooth()
					}
				}
			});
		})
	}

	// 蓝牙连接
	function findDevice() {
		return new Promise((resolve, reject) => {
			if (!deviceBtId.value) {
				console.log('未获取蓝牙设备名称')
				return;
			}
			// 开始扫描蓝牙设备
			bluetoothFindText.value = '正在查找设备..'
			startBluetoothDevicesDiscovery().then(() => {
				// 根据设备名称找到对应的蓝牙，并获取真实设备Id
				onBluetoothDeviceFound({
					keywords: deviceBtId.value,
				}).then(res => {
					deviceId.value = res.deviceId
					connectBt(deviceId.value)
				}).catch(() => {
					reject()
					wx.showModal({
						title: '设备连接失败',
						content: '未找到设备或设备已占用',
						showCancel: false,
					})
				})
			}).catch(() => {
				reject()
			})
		})
	}

	function connectBt(deviceId) {
		return new Promise((resolve, reject) => {
			bluetoothFindText.value = '正在连接设备...'
			// 连接蓝牙
			createBLEConnection({
				deviceId
			}).then(() => {
				resolve()
				// 获取蓝牙服务
				getBLEDeviceServices(deviceId).then(() => {
					// 获取蓝牙服务特征
					getBLEDeviceCharacteristics(deviceId).then(
						() => {})
				})
			}).catch(() => {
				uni.showModal({
					title: '设备连接失败',
					content: '请确保设备通电且您已开启蓝牙'
				})
			})
		})
	}

	// 根据设备id获取商品列表
	function getGoodsList() {
		return api.getGoodsList({
			device_id: deviceCode.value
		}).then(res => {
			const list = res.data.data
			goodsList.value = list;
			currentId.value = goodsList.value[0]?.id
		})
	}

	// 在未获取到设备id的时候，可以通过扫一扫二维码继续充电的逻辑
	function openScan() {
		uni.scanCode({
			scanType: ['qrCode'],
			success(res) {
				const url = res.result
				// if (!url.includes('koc365')) {
				// 	uni.$u.toast('设备二维码验证失败')
				// } else
				if (!url.includes(deviceKey)) {
					uni.$u.toast('获取设备号失败')
				} else {
					const id = getQueryString(url, deviceKey)
					deviceCode.value = id
					// uni.$u.toast(`获取成功：${deviceId}`)
					init()
				}
				// console.log('条码内容：' + res.result);
			}
		})
	}

	// 跳转到商家页面
	function routerToBusiness() {
		uni.navigateTo({
			url: `/pages/business/business`
		})
	}

	onLoad(async (query) => {
		if (query[deviceKey]) {
			deviceCode.value = query[deviceKey]
			deviceBtId.value = deviceCode.value
		} else if (query.q && query.q.includes(deviceKey)) {
			deviceCode.value = getQueryString(query.q, deviceKey)
			deviceBtId.value = deviceCode.value
		}
		// deviceCode.value = 'AKP47230631'
		// deviceBtId.value = 'AKP47230631'
		init()
	})

	onUnload(() => {
		console.log('onUnload close bluetooth')
		closeBluetooth()
	})
</script>

<style lang="scss" scoped>
	.page {
		--primary-color: #64c6ae;
	}

	.banner-img {
		width: 100%;
		height: 200px;
	}

	.layout {
		display: flex;
		flex-direction: column;
	}

	.module-title {
		padding-left: 10px;
		margin-bottom: 16px;
		border-left: 3px solid var(--primary-color);
		font-size: 14px;
		color: #333;
		font-weight: bold;
	}


	.cell-list {}

	.cell-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px;
		margin-bottom: 16px;
		color: #515151;
		border-radius: 8px;
		border: 1px solid #ebedf0;

		&.is-active {
			color: var(--primary-color);
			border-color: var(--primary-color);
			background-color: rgba(110, 198, 174, .2);
		}

		.content {
			display: flex;
			flex-direction: column;
		}

		.duration {
			font-size: 13px;
			margin-bottom: 5px;
		}

		.des {
			font-size: 12px;

		}

		.price {
			font-size: 14px;
		}
	}

	.tips {
		padding: 20px;
		display: flex;
		flex-direction: column;

		.title {
			margin-bottom: 10px;
			font-size: 14px;
			color: #333;
			text-align: center;
		}

		.des {
			font-size: 12px;
			color: #666;
		}
	}

	.contact-btn {
		display: inline;
		font-size: 14px;
		color: #666;
		background-color: rgba(0, 0, 0, 0);

		&:after {
			border: 0 none;
		}
	}
</style>